<template>
  <div class="text-voice">
    <Head></Head>
    <ButtonGroup @create="createDialogues"></ButtonGroup>
    <div class="dialogue" :style="{ height }">
      <div class="countdown">{{ countdown }}s</div>
      <div class="converzation" :style="{ height: converHeight }">
        <div class="default">
          <img :src="doctImg" alt="" />
          <div class="txt">
            您好，请描述您的症状或疾病，让我来为您智能推荐科室就诊！
          </div>
        </div>
        <div class="messages">
          <div
            class="messages-item"
            v-for="(message, index) in messages"
            :key="index"
            style="display: flex; justify-content: flex-end"
            :style="{
              justifyContent: message.isSelf ? 'flex-end' : 'flex-start',
            }"
          >
            <div class="selfs" v-if="message.isSelf">
              <div class="resTxt" :class="{ self: message.isSelf }">
                {{ message.inputTxt }}
              </div>
              <img :src="patientImg" alt="" />
            </div>
            <div class="opnents" v-else>
              <img :src="doctImg" alt="" />
              <div class="txt">
                <div
                  class="iptText"
                  v-html="formatText(message.inputTxt)"
                ></div>
                <div class="recommends" v-show="message.recommend">
                  <span style="font-weight: 600">推荐科室：</span><br />{{
                    message.recommend
                  }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="input" v-if="mode === 'text'">
      <div class="textarea">
        <!--   <el-input
          v-model="inputTxt"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 8 }"
          ref="inputRef"
          placeholder="请输入"
          @keyup.enter="sendMessage"
          keyboard="true"
        >
        </el-input> -->
        <!-- textarea  @input="adjustHeights" -->
        <textarea
          id="elem"
          ref="textareaRef"
          type="text"
          v-model="inputTxt"
          keyboard="true"
          autofocus
          rows="2"
          :style="textareaStyle"
          @focus="handleFocus"
        />
      </div>
      <el-button round @click="sendMessage">
        <SvgIcon name="send"></SvgIcon>
        <span>发送</span>
      </el-button>
    </div>
    <div class="inputVoice" v-else>
      <div class="textarea">
        <!--   <el-input
          v-model="inputTxt"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 8 }"
          ref="inputRef"
          placeholder="请输入"
          @keyup.enter="sendMessage"
          keyboard="true"
        >
        </el-input> -->

        <textarea
          id="voicearea"
          ref="textareaRef"
          type="text"
          v-model="inputTxt"
          rows="8"
          @input="autoHeight"
          :style="voiceareaStyle"
          placeholder="如需修改语音翻译内容，请先点击停止按钮..."
          @focus="Focus"
          @touchstart="startDelete"
          @touchend="stopDelete"
          @touchcancel="stopDelete"
        />
        <!--   <button
          class="clear-btn"
          id="clear-btn"
          @click="deleteCharacter"
          @touchstart="startDelete"
          @touchend="stopDelete"
          @touchcancel="stopDelete"
        >
          ×
        </button> -->
        <img
          :src="delImg"
          id="clear-btn"
          @click="deleteCharacter"
          @touchstart="startDelete"
          @touchend="stopDelete"
          @touchcancel="stopDelete"
          class="del-btn"
        />
      </div>
      <el-button round @click="sendMessage" style="width: 160px; height: 80px">
        <SvgIcon name="send" hight="60px"></SvgIcon>
        <span>发送</span>
      </el-button>
    </div>
    <div class="shiftVoice" v-show="mode === 'text'" @click="goVoices">
      <img :src="voiceImg" />
      <span>语音输入</span>
    </div>
    <div class="select">
      <div class="select-text" v-if="mode === 'text'"></div>
      <div class="select-voice" v-else>
        <div class="shiftText" @click="shiftText">
          <img :src="keyImg" alt="" class="backs" />
          <div class="stxt">文字输入</div>
        </div>
        <iframe
          src="/static/fancur.html"
          ref="iframeRef"
          width="100%"
          class="iframes"
          id="fancurFrame"
        ></iframe>
      </div>
    </div>
    <keyboard
      :transitionTime="'0.5s'"
      :maxQuantify="10"
      :showKeyboard="showKeyboard"
      @clickKey="clickKey"
      ref="keyboardRef"
      float
      :manyDict="manyDict"
      :singleDict="singleDict"
      @clickNumber="clickNumber"
      :blurHide="false"
    ></keyboard>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch, computed } from "vue";
import keyboard from "@/components/Keyboard/keyboardIndex.vue";
import { useWebSocket } from "@/composables/useWebSocket";
import type { CSSProperties } from "vue";
import delImg from "@/assets/icons/del.png";
import keyImg from "@/assets/images/keys.png";
import BasicDialog from "@/components/BasicDialog/index.vue";
import type { ApiResponse } from "@/types/websocket";
import voiceButtons from "@/views/guidence/Voice/components/voiceButtons.vue";
import { useRoute } from "vue-router";
import doctImg from "@/assets/images/doct.png";
import { getChatMessage } from "@/api/chat/index";
import patientImg from "@/assets/images/patient.png";
import { emitter } from "@/utils/mitt";
import type { Message } from "./type";
import { useRouter } from "vue-router";
import voiceImg from "@/assets/images/voice.png";
import { localStorageUtil } from "@/utils/localStorageUtil";

import { ElMessageBox, ElMessage } from "element-plus";
const isCreate = ref(false); //是否创建新对话
const keyboardRef = ref(null);
const router = useRouter();
const isDialogVisible = ref(true);
const route = useRoute();
const inputTxt = ref<string>("");
// 在组件外部声明

const countdown = ref(500);
const showKeyboard = ref(false);
const wsUrl = "ws://127.0.0.1:8800";
//const wsUrl = "ws://192.168.1.160:8800";

//点击键盘的值
const clickKey = (key: any) => {
  console.log("key-->>66666", key);
};

//点击键盘时数字的值
const clickNumber = (key: any) => {
  console.log("key-->>", key);
};

const formatText = (text: string) => {
  return text.replace(/\n/g, "<br>");
};
const manyDict = ref("dict/chowder.json");
const singleDict = ref("dict/baseDict.json");
const ways = ref("user"); //self 自触发  system 系统触发
let messageTxt: string;
const inputRef = ref<HTMLInputElement | null>(null);
let timer: any;
const messagesArr = localStorageUtil.get("messages");
const messages = ref<Message[]>(
  messagesArr && messagesArr.length > 0 ? messagesArr : []
);
let conversationId = ref("");
const lineHeight = 20; // 根据实际行高调整
const maxLines = 10;
const textareaRef = ref();
const recomendText = ref("");
const height = computed(() => (route.path === "/text" ? "49vh" : "52vh"));
const converHeight = computed(() => (route.path === "/text" ? "38vh" : "42vh"));
const shiftText = () => {
  router.push("/text");
};

const adjustHeight = () => {
  const textarea = textareaRef.value;
  textarea.style.height = "auto";

  const lines = inputTxt.value.split("\n").length;
  if (lines <= maxLines) {
    textarea.style.height =
      Math.min(textarea.scrollHeight, lineHeight * maxLines) + "px";
  } else {
    // 如果超过10行，截断内容（可选）
    inputTxt.value = inputTxt.value.split("\n").slice(0, maxLines).join("\n");
    textarea.style.height = lineHeight * maxLines + "px";
  }
};

const goVoices = () => {
  console.log("go voice");
  router.push("/voice");
};
const autoHeight = () => {
  if (textareaRef.value) {
    // 设置 textarea 的高度为自动，以便计算内容高度

    textareaRef.value.style.height = "auto";

    // 获取 scrollHeight，它表示内容的实际高度

    const scrollHeight = textareaRef.value.scrollHeight;

    // 设置 textarea 的高度为内容的实际高度

    textareaRef.value.style.height = `${scrollHeight}px`;
  }
};
let clearIntervalId: any;

const handleFocus = () => {
  showKeyboard.value = true;
};
const dialogRef = ref();
let currentInput: any;
const isClickStop = ref(false);
const textareaStyle: CSSProperties = {
  resize: "none",
  minHeight: "40px",
  // maxHeight: `${lineHeight * maxLines}px`,
  maxHeight: "200px",
  overflowY: "auto",
  width: "82%",
  padding: "15px",
  fontSize: "30px",
  border: "none",
};
const voiceareaStyle = {
  ...textareaStyle,
  width: "82%",
  maxHeight: "180px",
  borderRadius: "16px",
  //overflow: "hidden",
  overflow: "auto",
  marginLeft: "20px",
};
const emit = defineEmits(["open-basicdialog"]);
const startVisible = route.query.startVisible;
// 清空输入框的定时器

onMounted(() => {
  connect();

  window.addEventListener("message", handleMessage);

  if (route.path == "/text") {
    // 确保组件挂载后自动聚焦
    nextTick(() => {
      const textarea = textareaRef.value;
      if (textarea) {
        textarea.focus();
        showKeyboard.value = true;
      }
    });
  }

  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
      router.push("/home");
      localStorageUtil.clear();
    }
  }, 1000);
});
const props = defineProps({
  mode: {
    type: String,
    default: "text", //text 文字输入  voice 语音输入
  },
});

const { WSmessages, isConnected, send, connect, closews, stop } = useWebSocket(
  wsUrl,
  {
    onOpen: () => {
      console.log("WebSocket connected  httpsserver");
    },

    onMessage: (data: any) => {
      console.log("  https Received message:", data);
    },

    onError: (error: Event) => {
      console.error("WebSocket error:", error);
    },
  }
);
emitter.on("send-message", (message: Message) => {
  console.log(message);

  messages.value.push(message);
  localStorageUtil.set("messages", messages.value);

  nextTick(() => {
    const container = document.querySelector(".converzation");
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  });
});
//iframe子窗口传来的数据
const handleMessage = (event: any) => {
  if (event.data.type === "textareaEvent") {
    console.log(event.data, "eventdata");
    const { areaValue } = event.data.payload;

    inputTxt.value = areaValue;
  } else if (event.data.type === "startEvent") {
    stop();
    setTimeout(() => {
      connect();
    }, 500);
    const { stopPlay } = event.data.playload;

    if (stopPlay) {
      stop();
    }
  } else if (event.data.type === "clickStopBtn") {
    console.log(event.data, "clickStopBtn");
    const { isStopped, way, cursorPlace } = event.data.payload;

    isClickStop.value = isStopped;
    ways.value = way;
    /*   if (cursorPlace == "last") {
      //将textarea光标移动到最后 并显示光标
      const textArea = textareaRef.value;
      if (textArea) {
        textArea.focus();
        textArea.setSelectionRange(
          textArea.value.length,
          textArea.value.length
        ); // 将光标定位到文本框的最后
      }
    } */
    console.log(ways.value, "1111111111111");
  }
};
//向子窗口传递数据
function sendNumberToChild(data?: any, type?: string): Promise<void> {
  return new Promise((resolve, reject) => {
    const fancurFrame: any = document.getElementById("fancurFrame");
    if (fancurFrame) {
      fancurFrame.contentWindow.postMessage({ type: type, data: data }, "*");
      // 监听消息返回
      const messageHandler = (event: MessageEvent) => {
        if (event.data.type === `${type}Res`) {
          window.removeEventListener("message", messageHandler);
          resolve();
        }
      };
      window.addEventListener("message", messageHandler);
    } else {
      resolve();
    }
  });
}

const sendMessage = async () => {
  console.log(inputTxt.value, "输入框内容");

  //stop(); //停止播报

  closews(); //notice
  connect(); //notice

  if (inputTxt.value.trim() === "") {
    console.log("输入为空，不发送请求");
    ElMessage.error("输入不能为空");
    if (route.path === "/voice") {
      if (
        isClickStop.value &&
        inputTxt.value.trim() == "" &&
        ways.value === "user"
      ) {
        console.log("发送时，用户点击了停止，但是文本为空");
        sendNumberToChild(
          { startVisible: 0, stopColor: "#088AFD" },
          "stopColorEvent"
        );
      }
    }
    return;
  }

  if (route.path === "/voice") {
    if (!isClickStop.value && inputTxt.value.trim() !== "") {
      await sendNumberToChild(
        { isStopped: true, startVisible: 0, way: "system" },
        "clickStopEvent"
      );
    }

    if (
      isClickStop.value &&
      inputTxt.value.trim() !== "" &&
      ways.value === "user"
    ) {
      emitter.emit("send-message", { inputTxt: inputTxt.value, isSelf: true });
      messageTxt = inputTxt.value;
      inputTxt.value = "";
      sendNumberToChild(
        { startVisible: 0, stopColor: "#088AFD" },
        "stopColorEvent"
      );

      await sendRequest();
      isClickStop.value = false;
    }
  } else if (route.path === "/text") {
    if (inputTxt.value.trim() !== "") {
      emitter.emit("send-message", { inputTxt: inputTxt.value, isSelf: true });
      messageTxt = inputTxt.value;

      inputTxt.value = "";
      textareaRef.value.focus();
      await sendRequest();
    }
  }
};
// 监听 isClickStop 和 ways 的变化
const sendRequest = async () => {
  connect();
  try {
    const { gender, age } = localStorageUtil.get("userInfo");
    // console.log(messageTxt, "messageTxt");
    const message1 = messageTxt + "/no_think";

    const res = await getChatMessage(
      //messageTxt,
      //messageTxt,
      message1,
      conversationId.value,
      gender,
      age
    );

    let { answer, conversation_id, recommend } = res.result;
    inputTxt.value = "";
    isClickStop.value = false;
    answer = answer.replace(/<think>\n\n<\/think>\n\n/g, "");

    if (recommend.trim() == "") {
      if (answer.includes("\n")) {
        const paragraphs = answer
          .split("\n")
          .filter((p: any) => p.trim() !== "");

        paragraphs.forEach((paragraph: any) => {
          const processParagraph = paragraph.includes("*")
            ? paragraph.replace(/\*/g, "")
            : paragraph;
          console.log(processParagraph);
          //send(processParagraph);

          send(processParagraph);
        });
      } else {
        send(answer);
      }
    } else {
      const rstr = "推荐科室";
      send(rstr + recommend);
    }

    if (conversation_id) {
      conversationId.value = conversation_id;
    }
    emitter.emit("send-message", {
      inputTxt: answer,
      isSelf: false,
      recommend: recommend,
    });
  } catch (error) {
    console.log(error);
  }
};
watch(
  [isClickStop, ways], // 监听的变量数组

  ([newValue1, newValue2], [oldValue1, oldValue2]) => {
    console.log("isClickStop 变化:", oldValue1, "→", newValue1);
    isClickStop.value = newValue1;
    ways.value = newValue2;

    console.log("ways 变化:", oldValue2, "→", newValue2);
    console.log(isCreate.value, "isCreate.value");

    // 当 isClickStop 为 true 且 ways 为 "system" 时触发发送消息

    if (newValue1 === true && newValue2 === "system") {
      // 调试
      console.log("system触发数据1111", inputTxt.value);
      emitter.emit("send-message", { inputTxt: inputTxt.value, isSelf: true });
      messageTxt = inputTxt.value;
      sendRequest();
      isClickStop.value = false;
      ways.value = "user";
    }
  },

  { immediate: true } //
);
const createDialogues = async () => {
  stop();
  isCreate.value = true;
  console.log("当前页面路由", route.path);
  //close();
  console.log(messages.value, "清空之前messages");
  messages.value = [];
  localStorageUtil.remove("messages");
  conversationId.value = "";
  await nextTick();
  console.log("清空了messages", messages.value);

  emit("open-basicdialog");
  // 确保清除操作完成后再进行其他操作

  if (route.path == "/voice") {
    // await sendNumberToChild(
    //   { isStopped: true, startVisible: 0, way: "system" },
    //   "clickStopEvent"
    // );
    // sendNumberToChild({ startVisible: 0 }, "showStartEvent");
  }

  //router.go(0);会导致页面强制刷新 可能会出现闪退
};

onUnmounted(() => {
  console.log("组件卸载了。。。。");
  clearInterval(timer);

  closews();
  stopDelete(); // 确保组件卸载时停止定时器
  window.removeEventListener("message", handleMessage);
});
const voicearea = document.getElementById("voicearea") as HTMLTextAreaElement;
const clearBtn = document.getElementById(".clear-btn") as HTMLElement | null;
const deleteCharacter = () => {
  console.log("删除字符");
  const textarea = textareaRef.value as HTMLTextAreaElement | null;
  if (textarea) {
    const value = textarea.value; // 获取当前文本框的值
    let selectionStart = textarea.selectionStart || 0; // 获取光标起始位置
    const selectionEnd = textarea.selectionEnd || 0; // 获取光标结束位置

    // 如果有选中文本，则删除选中的部分
    if (selectionStart !== selectionEnd) {
      textarea.value =
        value.substring(0, selectionStart) + value.substring(selectionEnd);
      textarea.setSelectionRange(selectionStart, selectionStart); // 将光标移动到删除位置
    } else {
      // 如果没有选中文本，则删除光标前的一个字符
      if (selectionStart > 0) {
        textarea.value =
          value.substring(0, selectionStart - 1) +
          value.substring(selectionStart);
        // textarea.setSelectionRange(selectionStart - 1, selectionStart - 1); // 将光标移动到删除位置
        selectionStart = selectionStart - 1; // 光标移动到删除位置的前一位
      }
    }

    // 更新 v-model 绑定的数据
    inputTxt.value = textarea.value;
    // 使用 nextTick 确保 DOM 已更新
    nextTick(() => {
      if (textarea) {
        textarea.setSelectionRange(selectionStart, selectionStart);
        // 聚焦文本框以保持光标可见
        textarea.focus();
      }
    });
  }
};
const Focus = () => {
  const textarea = textareaRef.value as HTMLTextAreaElement | null;
  if (textarea) {
    textarea.focus(); // 确保获取焦点
  }
};

// const startDelete = () => {
//   deleteInterval = setInterval(deleteCharacter, 200);
// };

const stopDelete = () => {
  if (deleteInterval) {
    clearInterval(deleteInterval);
    deleteInterval = null;
  }
};

let deleteInterval: number | null = null;

const startDelete = () => {
  deleteInterval = setInterval(deleteCharacter, 150);
};
</script>
<style lang="scss" scoped>
@import "@/views/guidence/styles/common.scss";
.text-voice {
  @include container;
  .dialogue {
    width: 100%;
    // height: 45vh;

    position: relative;
    padding: 30px;
    border-top: 1px solid #449ae0;
    box-shadow: 0 -3px 4px rgba(0, 0, 0, 0.1);
    .countdown {
      position: absolute;
      top: 30px;
      right: 20px;
      font-size: 40px;
      color: #d82f2f;
      font-weight: 700;
    }
    .converzation {
      // height: 35vh;
      overflow-y: auto;

      margin-top: 7vh;
      .default {
        display: flex;
        align-items: center;
        .txt {
          @include txt-container;
        }
      }
      .messages {
        .messages-item {
          .selfs {
            display: flex;
            margin: 20px 0;
            align-items: center;
          }
          .resTxt.self {
            @include txt-container;
            @include fit-container;
            background: linear-gradient(to right, #2293e9, #06c0fb);
          }
          img {
            width: 140px;
            height: 140px;
            margin-left: 20px;
          }
          .opnents {
            @extend .default;

            .txt {
              @include txt-container;
              height: fit-content;
              width: fit-content;
            }
          }
        }
      }
    }
  }
  .input {
    position: relative;
    width: 100%;
    height: fit-content;
    // border: 1px solid #8bd2e4;
    box-shadow: inset 0 0 0 1px #d0d3da; /* 模拟内边框 */
    .textarea {
      .el-textarea {
        //  @include el-textarea-style;
      }
    }
    .el-button {
      position: absolute;
      right: 30px;
      bottom: 8%;
      width: 130px;
      height: 60px;
      background: #07c160;
      display: flex;
      align-items: center;
      padding: 0 20px;
      &:deep(:disabled) {
        background-color: #cccccc !important; /* 禁用时的背景颜色 */
        border-color: #cccccc !important; /* 禁用时的边框颜色 */
        color: #666666 !important; /* 禁用时的文本颜色 */
        cursor: not-allowed !important; /* 禁用时的光标样式 */
      }

      span {
        color: #ffffff;
        font-size: 30px;
      }
    }
  }
  .inputVoice {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    @extend .input;
    // height: 210px;
    // overflow: auto;
    background: #f7f7f7;

    padding: 10px 0;
    .textarea {
      width: 90%;
      position: relative;
      display: inline-block;
      #voicearea {
      }
      .clear-btn {
        position: absolute;

        right: 11.5vw;

        top: 3px;

        background: none;

        border: none;

        //cursor: pointer;

        font-size: 25px;
        touch-action: manipulation; //防止触摸延迟
      }
      .del-btn {
        position: absolute;
        top: 10%;
      }
    }
    .el-button {
      margin-bottom: 40px;
    }
  }
  .keyDown {
    background: #2c3e50;
  }
  .shiftText {
    display: flex;
    align-items: center;
    margin: 25px;
    height: 20px;

    .stxt {
      width: 130px;
      height: 50px;
      color: #409eff;
      font-size: 32px;
      margin-left: 5px;
      padding-top: 5px;
    }
  }
  .shiftVoice {
    position: fixed;
    bottom: 26vh;
    display: flex;
    align-items: center;
    span {
      color: #409eff;
      margin-left: 10px;
      font-size: 28px;
    }
  }
  .select-voice {
    display: flex;
    flex-direction: column;
    height: 22.4vh;
    overflow: hidden;
    background: #dedede;
    margin-top: 10px;
    position: fixed;
    bottom: 0;
    width: 100%;
    padding-bottom: 15px;
    .iframes {
      flex: 1;
      width: 90%;
      // border-radius: 16px;
      // overflow: hidden;
      // background: #ffffff;
      margin: 0 auto;
    }
  }
}
</style>
